var page = Page({
  data: {
    exercise_category: [],
    icon_list: ['juzhong', 'baolingqiu','taiquandao','jijian',  'huaban','quanji', 'qihang', 'paobu', 'yishuticao', 'lanqiu',  'yumaoqiu', 'pingpangqiu', 'wangqiu', 'ticao', 'qugunqiu',  'sheji', 'paiqiu', 'zuqiu',  'ganlanqiu', 'bangqiu']
  },

  navigateTolist(e) {
    var category = e.currentTarget.dataset.category;
    console.log("id:" + category.id);
    wx.navigateTo({
      url: '/pages/exercise/list/list?id=' + category.id + "&name=" + category.name
    })
  },

  onLoad() {
    // query exercise category
    wx.getStorage({
      key: "exercise_category",
      success: res => {
        var category = res.data || [];
        if (!category) {
          this.getCategory();
          return;
        } 
        this.setData({
          exercise_category: category
        });
      },
      fail: () => {
        this.getCategory();
      }
    });
  },

  getCategory() {
    let that = this;
    wx.showLoading({
      title: '',
    });
    console.log("start query category from cloud")

    const db = wx.cloud.database();
    db.collection('exercise_category').get({
      success: function(res) {
        console.log("from clound get category data: " + JSON.stringify(res));
        let category =  res.data || [];
        wx.hideLoading();
        that.setLocalStorage(category);
      },
    });
  },

  setLocalStorage(category) {
    console.log("set local storage");
    console.log("icon_list:" + JSON.stringify(this.data.icon_list));
    category.forEach((c,idx) => {
      console.log("icon_list:" + this.data.icon_list[idx]);
      c.icon_name = this.data.icon_list[idx]
    });
    console.log("category:" + JSON.stringify(category))
    this.setData({
      exercise_category: category
    });
    wx.setStorage({
      key: "exercise_category",
      data: category || [],
      success: function() {
        console.log("write exercise category success.")
      },
      fail: function() {
        console.log("write exercise category fail.")
      }
    });
  }
  
})